#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd=::socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        LOG(ERROR,"socket error");
        exit(2);
    }
    struct sockaddr_in serveraddr;
    memset(&serveraddr,0,sizeof(serveraddr));
    serveraddr.sin_family=AF_INET;
    serveraddr.sin_port=htons(serverport);
    serveraddr.sin_addr.s_addr=inet_addr(serverip.c_str());
    int n=connect(sockfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
    if(n<0)
    {
        LOG(ERROR,"connect error");
        exit(3);
    }
    while(true)
    {
        std::cout << "请输入要发送的消息: ";
        std::string outstring;
        std::getline(std::cin, outstring);

        ssize_t n=send(sockfd,outstring.c_str(),outstring.size(),0);
        if(n>0)
        {   
            char inbuffer[1024];
            ssize_t m=recv(sockfd,inbuffer,sizeof(inbuffer)-1,0);
            if(m>0)
            {
                inbuffer[m]=0;
                std::cout << "服务器回显: " << inbuffer << std::endl;
            }else if(m==0)
            {
                LOG(INFO,"server close");
                break;
            }else
            {
                LOG(ERROR,"recv error");
                break;
            }
        }
        else
        {
            break;
        }
    }
    shutdown(sockfd,SHUT_WR);
    //::close(sockfd);
    return 0;
}